class Compiler {
  constructor (vm) {
    this.el = vm.$el
    this.vm = vm
    this.compile(this.el)
  }

  compile (el) {
    const childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      if (this.isTextNode(node)) {
        this.compileText(node)
      } else if (this.isElementNode(node)) {
        this.compileElement(node)
      }

      if(node.childNodes && node.childNodes.length) this.compile(node)
    })
  }

  compileElement (node) {
    Array.from(node.attributes).forEach(attr => {
      let attrName = attr.name
      if(this.isDirective(attrName)) {
        // 删除自定义指令在dom上的显示
        node.removeAttribute(attrName)
        attrName = attrName.substr(2)
        let key = attr.value
        this.update(node, key, attrName)
      }
    })
  }

  update (node, key, attrName) {
    // 处理v-on:click v-bind:href这种类型
    // 未处理@ ：
    let extraprop
    if (attrName.includes(':')) {
      const arr = attrName.split(':')
      attrName = arr[0]
      extraprop = arr[1]
    }
    let updateFn = this[attrName + 'Updater']
    updateFn && updateFn.call(this, node, this.vm[key], key, extraprop)
  }

  textUpdater (node, value, key) {
    node.textContent = value
    new Watcher(this.vm, key, newValue => node.textContent = newValue)
  }

  modelUpdater (node, value, key) {
    node.value = value
    new Watcher(this.vm, key, newValue => node.value = newValue)
    node.addEventListener('input', () => this.vm[key] = node.value)
  }

  htmlUpdater (node, value, key) {
    node.innerHTML = value
    new Watcher(this.vm, key, newValue => node.innerHTML = newValue)
  }

  onUpdater (node, value, key, eventType) {
    // 只处理了data中的方法
    // 未处理简单js代码，未处理methods
    node.addEventListener(eventType, value)
    new Watcher(this.vm, key, newValue => {
      node.removeEventListener(eventType, value)
      node.addEventListener(eventType, newValue)
    })
  }
  // 追加了一个v-bind
  bindUpdater (node, value, key, attrName) {
    node.setAttribute(attrName, value)
    new Watcher(this.vm, key, newValue => node.setAttribute(attrName, newValue))
  }

  compileText (node) {
    let reg = /\{\{(.+?)\}\}/
    let value = node.textContent
    if (reg.test(value)) {
      let key = RegExp.$1.trim()
      node.textContent = value.replace(reg, this.vm[key])
      new Watcher(this.vm, key, newvalue => {
        node.textContent = newvalue
      })
    }
  }

  isDirective (attrName) {
    return attrName.startsWith('v-')
  }

  isTextNode (node) {
    return node.nodeType === 3
  }

  isElementNode (node) {
    return node.nodeType === 1
  }
}